import Vue from "vue";
import Vuex from "vuex";

import getters from "./getters";

Vue.use(Vuex);
import districtData from "@/components/amap/districtData";
import streetData from "@/components/amap/streetData";
import levelData from "@/components/amap/levelData";
import markData from "@/components/amap/marks";

const store = new Vuex.Store({
  state: {
    // 地图实例
    map: null,
    // 地图是否已初始化完成
    isMapReady: false,
    marks: [],
    showTraffic: false,
    showMapLabel: false,
    placeMarkerVisible: false
  },
  actions: {
    resetOverlay({ state, dispatch }) {
      if (!state.map) return
      state.map.clearMap();
      dispatch("focusMainDistrict");
    },
    setZoomAndCenter({ state }, { zoom, center }) {
      if (!state.map) return
      state.map.setZoomAndCenter(zoom, center);
    },
    resetCenterAndZoom({ state }) {
      if (!state.map) return
      state.map.setZoomAndCenter(13.76, [120.4242, 36.186256]);
    },
    setZoom({ state }, zoom) {
      if (!state.map) return
      state.map.setZoom(zoom);
    },
    focusMainDistrict({ state, dispatch }) {
      if (!state.map) return
      state.map.clearMap();
      // 外多边形坐标数组和内多边形坐标数组
      var outer = [
        new AMap.LngLat(-360, 90, true),
        new AMap.LngLat(-360, -90, true),
        new AMap.LngLat(360, -90, true),
        new AMap.LngLat(360, 90, true),
      ];

      var pathArray = [outer, districtData];

      var polygon = new AMap.Polygon({
        pathL: pathArray,
        strokeColor: "#0099ff",
        strokeWeight: 8,
        fillColor: "#24494A",
        fillOpacity: 0.5,
      });
      polygon.setPath(pathArray);
      state.map.add(polygon);
    },
    // 遮罩地图并聚焦街道
    focusStreetByName({ state }, name) {
      if (!state.map) return
      state.map.clearMap();
      const street = streetData[name];
      const data = street.boundaries;
      state.map.setZoomAndCenter(15, street.center);
      var outer = [
        new AMap.LngLat(-360, 90, true),
        new AMap.LngLat(-360, -90, true),
        new AMap.LngLat(360, -90, true),
        new AMap.LngLat(360, 90, true),
      ];

      var pathArray = [outer, data];
      var polygon = new AMap.Polygon({
        pathL: pathArray,
        strokeColor: "#0099ff",
        strokeWeight: 8,
        fillColor: "#24494A",
        fillOpacity: 0.5,
      });
      polygon.setPath(pathArray);
      state.map.add(polygon);
    },
    addStreetZone({ state, dispatch }, name) {
      const data = streetData[name].boundaries;
      dispatch("addPolygon", { data: data, level: "street", name });

      // AMap.convertFrom(data, "gps", (status, result) => {
      //   if (result.info === "ok") {
      //     console.log(name, JSON.stringify(result.locations), '!')
      //     var lnglats = result.locations; // Array.<LngLat>
      //     dispatch("addPolygon", { data: lnglats, level: "street", name });
      //   }
      // });
    },
    drawAllStreetZone({ state, dispatch }, paylaod) {
      if (!state.map) return
      state.map.clearMap();
      for (let name in streetData) {
        dispatch("addStreetZone", name);
        const s = streetData[name];
        let text = name;
        let angle = 0;
        let position = s.center;
        switch (name) {
          case "loushan":
            text = "楼山街道";
            break;
          case "xiangtanlu":
            text = "湘潭路街道";
            break;
          case "xingchenglu":
            text = "兴城路街道";
            break;
          case "xinghualu":
            text = "兴华路街道";
            angle = 90;
            break;
          case "hushanlu":
            text = "虎山路街道";
            break;
          case "zhenhualu":
            text = "振华路街道";
            break;
          case "licun":
            text = "李村街道";
            break;
          case "fushanlu":
            text = "浮山路街道";
            break;
          case "jiushui":
            text = "九水街道";
            break;
          case "shiyuan":
            text = "世园街道";
            break;
          case "cangkou":
            text = "沧口街道";
            break;
        }
        // 创建纯文本标记
        var txt = new AMap.Text({
          text: text,
          anchor: "center", // 设置文本标记锚点
          draggable: false,
          clickable: true,
          angle: angle,
          style: {
            "background-color": "transparent",
            "text-align": "center",
            "font-size": "30px",
            color: "#fff",
            border: "none",
            "font-weight": "bold",
            "pointer-event": 'none'
          },
          position: position,
        });
        txt.on('click', () => {
          const event = new CustomEvent("onAreaClick", {
            detail: { name: text, level: 'street', data: position },
          });
          window.dispatchEvent(event);
        })
        txt.setMap(state.map);
      }
    },
    addPolygon({ state }, { data, level, name }) {
      if (!state.map) return
      let polygon = new AMap.Polygon({
        path: data,
        fillColor: "rgba(93,125,147, 0.1)",
        strokeOpacity: 1,
        fillOpacity: 0.5,
        strokeColor: "rgba(0,153,255, 1)",
        strokeWeight: 6,
        strokeStyle: "solid",
        // strokeDasharray: [5, 5],
        bubble: true,
      });
      polygon.on("mouseover", () => {
        polygon.setOptions({
          fillOpacity: 0.8,
          fillColor: "#00D2FF",
        });
      });
      polygon.on("mouseout", () => {
        polygon.setOptions({
          fillOpacity: 0.5,
          fillColor: "rgba(93,125,147, 0.1)",
        });
      });
      polygon.on("click", () => {
        const event = new CustomEvent("onAreaClick", {
          detail: { name, level, data },
        });
        window.dispatchEvent(event);
      });
      state.map.add(polygon);
    },
    markBoundsByData({ state, dispatch }, { data, level, name }) {
      dispatch("addPolygon", { data, level, name });

      // AMap.convertFrom(data, "gps", (status, result) => {
      //   if (result.info === "ok") {
      //     console.log(name, JSON.stringify(result.locations))
      //     var lnglats = result.locations; // Array.<LngLat>
      //   }
      // });
    },
    focusTourismZone({ state, dispatch }) {
      // 聚焦青岛世博园区域 坐标需要转换
      const data = levelData.culture.boundaries;
      if (!state.map) return
      state.map.clearMap();
      // 外多边形坐标数组和内多边形坐标数组
      var outer = [
        new AMap.LngLat(-360, 90, true),
        new AMap.LngLat(-360, -90, true),
        new AMap.LngLat(360, -90, true),
        new AMap.LngLat(360, 90, true),
      ];

      var pathArray = [outer, data];

      var polygon = new AMap.Polygon({
        pathL: pathArray,
        strokeColor: "#0099ff",
        strokeWeight: 8,
        fillColor: "#24494A",
        fillOpacity: 0.5,
      });
      polygon.setPath(pathArray);
      var txt = new AMap.Text({
        text: '青岛世界园艺博览园',
        anchor: "center", // 设置文本标记锚点
        draggable: false,
        clickable: false,
        angle: 0,
        style: {
          "background-color": "transparent",
          "text-align": "center",
          "font-size": "30px",
          color: "#fff",
          border: "none",
          "font-weight": "bold",
        },
        position: levelData.culture.center,
      });
      const marks = markData.culture
      const txts = []
      const positions = marks.map(item => item.position)
      marks.forEach(item => {
        dispatch('addMarks', {
          data: positions,
          iconSrc: require("@/assets/images/licang/dw/wl.png")
        })
        const txt = new AMap.Text({
          text: item.name,
          anchor: "center", // 设置文本标记锚点
          draggable: false,
          clickable: false,
          angle: 0,
          style: {
            "background-color": "transparent",
            "text-align": "center",
            "font-size": "26px",
            color: "#fff",
            border: "none",
            "font-weight": "bold",
          },
          offset: [0, 28],
          position: item.position,
        });
        txts.push(txt)
      })
      
      state.map.add([polygon, txt].concat(txts));
      state.map.setZoomAndCenter(16, levelData.culture.center)
    },
    drawAllCommunities({ state, dispatch }) {
      const d = levelData.lv1;
      d.forEach((item) => {
        let text = item.name;
        dispatch("markBoundsByData", {
          data: item.boundaries,
          level: "communities",
          name: text,
        });
        let angle = 0;
        if (text === "金液泉路小区社区" || text === '旭东社区' || text === '台柳路社区') {
          angle = 75;
        }
        var txt = new AMap.Text({
          text: text,
          anchor: "center", // 设置文本标记锚点
          draggable: false,
          clickable: true,
          angle: angle,
          style: {
            "background-color": "transparent",
            "text-align": "center",
            "font-size": "20px",
            color: "#fff",
            border: "none",
            "font-weight": "bold",
          },
          position: item.center,
        });
        txt.on('click', () => {
          const event = new CustomEvent("onAreaClick", {
            detail: { name: text, level: 'communities', data: item.boundaries },
          });
          window.dispatchEvent(event);
        })
        txt.setMap(state.map);
        state.map.setFitView();
        state.map.setZoom(16)
      });
    },
    drawCommunity({ dispatch, state }) {
      const d = levelData.lv2;
      d.forEach((item) => {
        let text = item.name;
        dispatch("markBoundsByData", {
          data: item.boundaries,
          level: "community",
          name: text,
        });
        let angle = 0;
        if (text === "台柳路社区中小区") {
          angle = 90;
        }
        var txt = new AMap.Text({
          text: text,
          anchor: "center", // 设置文本标记锚点
          draggable: false,
          clickable: true,
          angle: angle,
          style: {
            "background-color": "transparent",
            "text-align": "center",
            "font-size": "30px",
            color: "#fff",
            border: "none",
            "font-weight": "bold",
          },
          position: item.center,
        });
        txt.on('click', () => {
          const event = new CustomEvent("onAreaClick", {
            detail: { name: text, level: 'community', data: item.boundaries },
          });
          window.dispatchEvent(event);
        })
        txt.setMap(state.map);
        state.map.setFitView();
        state.map.setZoom(17)
      });
    },
    drawPlace({ state, dispatch, commit }) {
      const d = levelData.lv3
      const txts = []
      d.forEach((item, index) => {
        let name = `福岛小区${index+1}号楼`
        var txt = new AMap.Text({
          text: name,
          anchor: "center", // 设置文本标记锚点
          draggable: false,
          clickable: true,
          angle: 0,
          style: {
            "background-color": "rgba(80, 106, 118, 0.8)",
            "text-align": "center",
            "font-size": "26px",
            color: "#fff",
            border: "2px solid rgba(86, 151, 252, 1)",
            "font-weight": "bold",
            padding: '20px 40px'
          },
          offset: [0, 0],
          position: item,
        });
        txt.on('click', () => {
          const event = new CustomEvent("onAreaClick", {
            detail: { name, level: 'place', data: item },
          });
          window.dispatchEvent(event);
        })
        txts.push(txt)
      })
      state.map.add(txts)
      state.map.setFitView()
      state.map.setZoom(20)
    },
    drawBuilding({ state }, item) {
      state.map.clearMap()
      const name = item.name
      var txt = new AMap.Text({
        text: name,
        anchor: "center", // 设置文本标记锚点
        draggable: false,
        clickable: true,
        angle: 0,
        style: {
          "background-color": "rgba(80, 106, 118, 0.8)",
          "text-align": "center",
          "font-size": "26px",
          color: "#fff",
          border: "2px solid rgba(86, 151, 252, 1)",
          "font-weight": "bold",
          padding: '20px 40px'
        },
        offset: [0, 0],
        position: item.data,
      });
      txt.on('click', () => {
        const event = new CustomEvent("onAreaClick", {
          detail: { name, level: 'building', data: item },
        });
        window.dispatchEvent(event);
      })
      state.map.add(txt)
      state.map.setZoomAndCenter(20, item.data)
    },
    setMapLevel({ state, dispatch }, level) {
      if (!state.map) return
      state.map.clearMap();
      if (level === 2) {
        dispatch('drawAllCommunities')
      }
      if (level === 3) {
        // 某社区下的所有小区
        dispatch("drawCommunity");
      }
      if (level === 4) {
        // 某小区的所有楼
        dispatch("drawPlace");
      }
    },
    addMarks({ state, commit }, { data, onClick, type, iconSrc, markSize=[60, 79.5] }) {
      if (!state.map) return
      console.log({ data, onClick, type, iconSrc, markSize })
      let icon =
        type === 1
          ? require("@/assets/images/licang/dw/jg.png")
          : require("@/assets/images/licang/dw/cy.png");
      if (iconSrc) {
        icon = iconSrc
      }
      const marks = [];
      data.forEach((item) => {
        var mark = new AMap.LabelMarker({
          position: item,
          icon: {
            image: icon,
            size: markSize
            // offset: new AMap.Pixel(-13, -30),
          }
        })
        mark.on("click", () => {
          onClick && onClick(item);
        });
        marks.push(mark);
      });
      console.log(marks)
      state.map.add(marks);
    },
    addConstantMarks({ state }, { type, onClick, markSize=[60, 79.5] }) {
      if (!state.map) return
      const iconB = require("@/assets/images/licang/dw/blue-green.png");
      const iconT = require("@/assets/images/licang/dw/green.png");
      const data1 = markData.tourMarks;
      const marks = [];
      if (type === "tourism" || type === 'all') {
        data1.forEach((item) => {
          // var mark = new AMap.Marker({
          //   position: item.position,
          //   // 将一张图片的地址设置为 icon
          //   icon: iconT,
          //   // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
          //   offset: new AMap.Pixel(-13, -30),
          // });
          var mark = new AMap.LabelMarker({
            position: item.position,

            icon: {
              image: iconT,
              size: markSize
              // offset: new AMap.Pixel(-13, -30),
            }
          })

          mark.on("click", () => {
            onClick && onClick(item);
          });
          marks.push(mark);
          var txt = new AMap.Text({
            text: item.name,
            anchor: "center", // 设置文本标记锚点
            draggable: false,
            clickable: true,
            angle: 0,
            style: {
              "background-color": "transparent",
              "text-align": "center",
              "font-size": "26px",
              color: "#fff",
              border: "none",
              "font-weight": "bold",
            },
            offset: [0, 28],
            position: item.position,
          });

          txt.setMap(state.map);
        });
      }

      if (type === "business" || type === 'all') {
        const data2 = markData.businessMarks;
        data2.forEach((item) => {
          // var mark = new AMap.Marker({
          //   position: item.position,
          //   // 将一张图片的地址设置为 icon
          //   icon: iconB,
          //   // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
          //   offset: new AMap.Pixel(-13, -30),
          // });
          var mark = new AMap.LabelMarker({
            position: item.position,
            icon: {
              image: iconB,
              size: markSize
              // offset: new AMap.Pixel(-13, -30),
            }
          })
          mark.on("click", () => {
            onClick(item);
          });
          marks.push(mark);
          var txt = new AMap.Text({
            text: item.name,
            anchor: "center", // 设置文本标记锚点
            draggable: false,
            clickable: true,
            angle: 0,
            style: {
              "background-color": "transparent",
              "text-align": "center",
              "font-size": "26px",
              color: "#fff",
              border: "none",
              "font-weight": "bold",
            },
            offset: [0, 28],
            position: item.position,
          });

          txt.setMap(state.map);
        });
      }

      state.map.add(marks);
    },
    openInfoWindow({ state }, detail) {
      const event = new CustomEvent("openInfoWindow", {
        detail
      });
      window.dispatchEvent(event);
    },
  },
  mutations: {
    SET_MAP_STATUS(state, status) {
      state.isMapReady = status;
    },
    SAVE_MAP_INSTANCE(state, mapIns) {
      state.map = mapIns;
    },
    SET_SHOW_TRAFFIC(state, val) {
      state.showTraffic = val
    },
    SET_SHOW_LABEL(state, val) {
      state.showMapLabel = val
    },
    SET_PLACE_MARKERS_VISIBLE(state, val) {
      state.placeMarkerVisible = val
    }
  },
  modules: {},
  getters,
});

export default store;
